package com.liyao.windowtest4;

import com.liyao.windowtest4.Utils.PasswordConfig;
import javafx.application.Application;
import javafx.fxml.FXMLLoader;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.scene.control.*;
import javafx.stage.Stage;
import net.sf.json.JSONObject;
import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.context.ConfigurableApplicationContext;

import java.io.*;
import java.nio.file.Path;
import java.nio.file.Paths;

/**
 * @program: windowtest4
 * @description: JavaFXApp
 * @author: liu yan
 * @create: 2024-10-12 22:40
 */
public class JavaFXApp extends Application {
    private ConfigurableApplicationContext context;

    public static String CORRECT_PASSWORD; // 预设的正确密码

    @Override
    public void init() throws Exception {
        // 获取项目的同级目录路径
        String projectDir = System.getProperty("user.dir");
        // 创建config文件夹的路径
        String configDirPath = projectDir + File.separator + "config";

        // 创建config文件夹（如果不存在）
        File configDir = new File(configDirPath);
        if (!configDir.exists()) {
            configDir.mkdir();
            System.out.println("创建config文件夹成功");
            try {
                InputStream inputStream = getClass().getClassLoader().getResourceAsStream("application.properties");
                if(inputStream==null){
                    System.err.println("未找到系统文件：application.properties");
                }else {
                    System.out.println("created application.properties file");
                }

                BufferedReader br = new BufferedReader(new InputStreamReader(inputStream));

                String line;
                while ((line = br.readLine()) != null) {
                    // 写入
                    try (FileOutputStream fos=new FileOutputStream(configDirPath + File.separator +"application.properties",true);
                         BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(fos,"UTF-8"))) {
                            writer.write(line);
                            writer.newLine();
                    }
                }
            } catch (IOException e) {
                System.err.println("application.properties 读取失败");
                e.printStackTrace();
            }
            try {
                InputStream inputStream = getClass().getClassLoader().getResourceAsStream("data.txt");
                if(inputStream==null){
                    System.err.println("未找到系统文件：data.txt");
                }else{
                    System.out.println("created data.txt file");
                }

                try (FileOutputStream fos=new FileOutputStream(configDirPath + File.separator +"data.txt",true);
                     BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(fos,"UTF-8"))) {
                    writer.write("");
                }

                BufferedReader br = new BufferedReader(new InputStreamReader(inputStream));

                String line;
                while ((line = br.readLine()) != null) {
                    // 写入
                    try (FileOutputStream fos=new FileOutputStream(configDirPath + File.separator +"data.txt",true);
                         BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(fos,"UTF-8"))) {
                        writer.write(line);
                        writer.newLine();
                    }
                }
            } catch (IOException e) {
                System.err.println("data.txt 读取失败");
                e.printStackTrace();
            }
            try {
                InputStream inputStream = getClass().getClassLoader().getResourceAsStream("Routine.txt");
                if(inputStream==null){
                    System.err.println("未找到系统文件：Routine.txt");
                }else{
                    System.out.println("created Routine.txt file");
                }

                try (FileOutputStream fos=new FileOutputStream(configDirPath + File.separator +"Routine.txt",true);
                     BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(fos,"UTF-8"))) {
                    writer.write("");
                }

                BufferedReader br = new BufferedReader(new InputStreamReader(inputStream));

                String line;
                while ((line = br.readLine()) != null) {
                    // 写入
                    try (FileOutputStream fos=new FileOutputStream(configDirPath + File.separator +"Routine.txt",true);
                         BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(fos,"UTF-8"))) {
                        writer.write(line);
                        writer.newLine();
                    }
                }
            } catch (IOException e) {
                System.err.println("Routine.txt 读取失败");
                e.printStackTrace();
            }

            try {
                InputStream inputStream = getClass().getClassLoader().getResourceAsStream("taskItems.txt");
                if(inputStream==null){
                    System.err.println("未找到系统文件：taskItems.txt");
                }else{
                    System.out.println("created taskItems.txt file");
                }

                try (FileOutputStream fos=new FileOutputStream(configDirPath + File.separator +"taskItems.txt",true);
                     BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(fos,"UTF-8"))) {
                    writer.write("");
                }

                BufferedReader br = new BufferedReader(new InputStreamReader(inputStream));

                String line;
                while ((line = br.readLine()) != null) {
                    // 写入
                    try (FileOutputStream fos=new FileOutputStream(configDirPath + File.separator +"taskItems.txt",true);
                         BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(fos,"UTF-8"))) {
                        writer.write(line);
                        writer.newLine();
                    }
                }
            } catch (IOException e) {
                System.err.println("taskItems.txt 读取失败");
                e.printStackTrace();
            }

            try {
                InputStream inputStream = getClass().getClassLoader().getResourceAsStream("torqueItems.txt");
                if(inputStream==null){
                    System.err.println("未找到系统文件：torqueItems.txt");
                }else{
                    System.out.println("created torqueItems.txt file");
                }

                try (FileOutputStream fos=new FileOutputStream(configDirPath + File.separator +"torqueItems.txt",true);
                     BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(fos,"UTF-8"))) {
                    writer.write("");
                }

                BufferedReader br = new BufferedReader(new InputStreamReader(inputStream));

                String line;
                while ((line = br.readLine()) != null) {
                    // 写入
                    try (FileOutputStream fos=new FileOutputStream(configDirPath + File.separator +"torqueItems.txt",true);
                         BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(fos,"UTF-8"))) {
                        writer.write(line);
                        writer.newLine();
                    }
                }
            } catch (IOException e) {
                System.err.println("torqueItems.txt 读取失败");
                e.printStackTrace();
            }
        }else{
            // application.properties
            File fileToCheck = new File(configDirPath + File.separator + "application.properties");
            if (fileToCheck.exists()) {
                System.out.println("文件存在：" + configDirPath + File.separator + "application.properties");
            } else {
                System.out.println("文件不存在：" + configDirPath + File.separator + "application.properties");
                try {
                    InputStream inputStream = getClass().getClassLoader().getResourceAsStream("application.properties");
                    if(inputStream==null){
                        System.err.println("未找到系统文件：data.txt");
                    }

                    BufferedReader br = new BufferedReader(new InputStreamReader(inputStream));

                    String line;
                    while ((line = br.readLine()) != null) {
                        // 写入
                        try (FileOutputStream fos=new FileOutputStream(configDirPath + File.separator +"application.properties",true);
                             BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(fos,"UTF-8"))) {
                            writer.write(line);
                            writer.newLine();
                        }
                    }
                } catch (IOException e) {
                    System.err.println("application.properties 读取失败");
                    e.printStackTrace();
                }
            }
            // data.txt
            File fileToCheckDataTxt = new File(configDirPath + File.separator + "data.txt");
            if (fileToCheckDataTxt.exists()) {
                System.out.println("文件存在：" + configDirPath + File.separator + "data.txt");
            } else {
                System.out.println("文件不存在：" + configDirPath + File.separator + "data.txt,即将写入...");
                try {
                    InputStream inputStream = getClass().getClassLoader().getResourceAsStream("data.txt");
                    if(inputStream==null){
                        System.err.println("未找到系统文件：data.txt");
                    }

                    BufferedReader br = new BufferedReader(new InputStreamReader(inputStream));

                    String line;
                    if(br.readLine()!=null){
                        while ((line = br.readLine()) != null) {
                            // 写入
                            try (FileOutputStream fos=new FileOutputStream(configDirPath + File.separator +"data.txt",true);
                                 BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(fos,"UTF-8"))) {
                                writer.write(line);
                                writer.newLine();
                            }
                        }
                    }else{
                        try (FileOutputStream fos=new FileOutputStream(configDirPath + File.separator +"data.txt",true);
                             BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(fos,"UTF-8"))) {
                            writer.write("");
                            writer.newLine();
                        }
                    }
                    System.out.println("文件：" + configDirPath + File.separator + "data.txt,写入成功");

                } catch (IOException e) {
                    System.err.println("data.txt 读取失败");
                    e.printStackTrace();
                }
            }

            // Routine.txt
            File fileToCheckRoutineTxt = new File(configDirPath + File.separator + "Routine.txt");
            if (fileToCheckRoutineTxt.exists()) {
                System.out.println("文件存在：" + configDirPath + File.separator + "Routine.txt");
            } else {
                System.out.println("文件不存在：" + configDirPath + File.separator + "Routine.txt,即将写入...");
                try {
                    InputStream inputStream = getClass().getClassLoader().getResourceAsStream("Routine.txt");
                    if(inputStream==null){
                        System.err.println("未找到系统文件：data.txt");
                    }

                    BufferedReader br = new BufferedReader(new InputStreamReader(inputStream));

                    String line;
                    if(br.readLine()!=null){
                        while ((line = br.readLine()) != null) {
                            // 写入
                            try (FileOutputStream fos=new FileOutputStream(configDirPath + File.separator +"Routine.txt",true);
                                 BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(fos,"UTF-8"))) {
                                writer.write(line);
                                writer.newLine();
                            }
                        }
                    }else{
                        //写入空白
                        try (FileOutputStream fos=new FileOutputStream(configDirPath + File.separator +"Routine.txt",true);
                             BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(fos,"UTF-8"))) {
                            writer.write("");
                            writer.newLine();
                        }
                    }

                } catch (IOException e) {
                    System.err.println("Routine.txt 读取失败");
                    e.printStackTrace();
                }
            }

            // taskItems.txt
            File fileToCheckTaskItemsTxt = new File(configDirPath + File.separator + "taskItems.txt");
            if (fileToCheckTaskItemsTxt.exists()) {
                System.out.println("文件存在：" + configDirPath + File.separator + "taskItems.txt");
            } else {
                System.out.println("文件不存在：" + configDirPath + File.separator + "taskItems.txt,即将写入...");
                try {
                    InputStream inputStream = getClass().getClassLoader().getResourceAsStream("taskItems.txt");
                    if(inputStream==null){
                        System.err.println("未找到系统文件：data.txt");
                    }
                    BufferedReader br = new BufferedReader(new InputStreamReader(inputStream));
                    String line;
                    if(br.readLine()!=null){
                        while ((line = br.readLine()) != null) {
                            // 写入
                            try (FileOutputStream fos=new FileOutputStream(configDirPath + File.separator +"taskItems.txt",true);
                                 BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(fos,"UTF-8"))) {
                                writer.write(line);
                                writer.newLine();
                            }
                        }
                    }else{
                        //写入空白
                        try (FileOutputStream fos=new FileOutputStream(configDirPath + File.separator +"taskItems.txt",true);
                             BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(fos,"UTF-8"))) {
                            writer.write("");
                            writer.newLine();
                        }
                    }

                } catch (IOException e) {
                    System.err.println("taskItems.txt 读取失败");
                    e.printStackTrace();
                }
            }

            // torqueItems.txt
            File fileToCheckTorqueItemsTxt = new File(configDirPath + File.separator + "torqueItems.txt");
            if (fileToCheckTorqueItemsTxt.exists()) {
                System.out.println("文件存在：" + configDirPath + File.separator + "torqueItems.txt");
            } else {
                System.out.println("文件不存在：" + configDirPath + File.separator + "torqueItems.txt,即将写入...");
                try {
                    InputStream inputStream = getClass().getClassLoader().getResourceAsStream("torqueItems.txt");
                    if(inputStream==null){
                        System.err.println("未找到系统文件：data.txt");
                    }

                    BufferedReader br = new BufferedReader(new InputStreamReader(inputStream));

                    String line;
                    if(br.readLine()!=null){
                        while ((line = br.readLine()) != null) {
                            // 写入
                            try (FileOutputStream fos=new FileOutputStream(configDirPath + File.separator +"torqueItems.txt",true);
                                 BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(fos,"UTF-8"))) {
                                writer.write(line);
                                writer.newLine();
                            }
                        }
                    }else{
                        // 写入空白
                        try (FileOutputStream fos=new FileOutputStream(configDirPath + File.separator +"torqueItems.txt",true);
                             BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(fos,"UTF-8"))) {
                            writer.write("");
                            writer.newLine();
                        }
                    }

                } catch (IOException e) {
                    System.err.println("torqueItems.txt 读取失败");
                    e.printStackTrace();
                }
            }
        }

        CORRECT_PASSWORD = PasswordConfig.getCorrectPassword(); // 预设的正确密码

        context = new SpringApplicationBuilder(Windowtest4Application.class).run();
    }

    @Override
    public void start(Stage stage) throws Exception {
        FXMLLoader loader=new FXMLLoader();
        loader.setControllerFactory(context::getBean);
        loader.setLocation(JavaFXApp.class.getResource("/view/MainLayout.fxml"));
//        loader.setLocation(JavaFXApp.class.getResource("/view/management.fxml"));
        Parent parent=loader.load();
        Scene scene = new Scene(parent);
        stage.setTitle("扭力扳手管理系统");
        stage.setScene(scene);

        // 设置关闭窗口事件处理器
        stage.setOnCloseRequest(event -> {
            // 创建一个包含密码输入框的对话框
            Dialog<Void> dialog = new Dialog<>();
            dialog.setTitle("请输入管理密码");
            dialog.setHeaderText("请输入正确的管理密码来关闭应用程序。");

            // 创建密码输入框
            PasswordField passwordField = new PasswordField();
            passwordField.setPromptText("密码:");

            // 设置对话框内容
            DialogPane dialogPane = dialog.getDialogPane();
            dialogPane.setContent(passwordField);

            // 设置对话框按钮（这里只设置了一个“关闭”按钮）
            ButtonType closeButtonType = new ButtonType("关闭程序", ButtonBar.ButtonData.OK_DONE);
            dialog.getDialogPane().getButtonTypes().add(closeButtonType);

            // 添加按钮点击事件处理器
            dialog.setResultConverter(dialogButton -> {
                if (dialogButton == closeButtonType) {
                    String inputPassword = passwordField.getText();
                    if (CORRECT_PASSWORD.equals(inputPassword)) {
                        // 密码正确，允许关闭窗口
                        event.consume(); // 取消默认关闭行为（因为我们要手动关闭）
                        System.exit(0); // 退出应用程序
                        return null; // 不需要返回结果
                    } else {
                        // 密码错误，显示错误消息并阻止关闭窗口
                        showPasswordErrorAlert();
                        event.consume(); // 取消默认关闭行为
                        return null; // 不需要返回结果
                    }
                }
                return null; // 对于其他按钮，不执行任何操作
            });

            dialog.setOnCloseRequest(dialogButton -> {
                event.consume(); // 取消默认关闭行为
            });

            // 显示对话框
            dialog.showAndWait();
        });

        stage.show();
    }

    // 显示密码错误提示的对话框
    private void showPasswordErrorAlert() {
        Alert alert = new Alert(Alert.AlertType.ERROR);
        alert.setTitle("密码错误");
        alert.setHeaderText("无效的密码");
        alert.setContentText("输入的密码不正确，无法关闭应用程序");
        alert.showAndWait();
    }

    @Override
    public void stop() {
        // 关闭Spring Boot上下文
        context.close();
    }

    public static void main(String[] args) {
        launch(args);
    }
}
